<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入慈善活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['Community:charity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['Community:charity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['Community:charity:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="charityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" :index="createIndex" />
      <el-table-column label="慈善活动名称" align="center" prop="name" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="海报图片" align="center" prop="postUrl" >
         <!-- 图片的显示 -->
                 <template   slot-scope="scope">            
                    <img :src="scope.row.postUrl"  min-width="70" height="70" 
                           @click="previewPic(scope.row.postUrl)" />
                 </template>     
      </el-table-column>
      <el-table-column label="已捐赠金额" align="center" prop="donorMoney" />
      <el-table-column label="目标金额" align="center" prop="targetMoney" />
      <el-table-column label="慈善活动开始时间" align="center" prop="startTime" width="180">
      </el-table-column>
      <el-table-column label="慈善活动结束时间" align="center" prop="endTime" width="180">
      </el-table-column>
      <el-table-column label="收藏人数" align="center" prop="collectNumber" />
      <el-table-column label="捐赠人数" align="center" prop="charityNumber" />
      <el-table-column label="状态" align="center" prop="status" >
         <template slot-scope="scope">
          <el-switch  v-model="scope.row.status"
                  active-color="#13ce66"
                 inactive-color="#ff4949"
                :active-value="0"
                :inactive-value="2"
                @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否开启置顶 1 开启 0 未开启" align="center" prop="isCarousel" >
         <template slot-scope="scope">
          <el-switch  v-model="scope.row.isCarousel"
                 active-color="#13ce66"
                 inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="handleIsCarouselChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="详情显示状态" align="center" prop="showStatus">
         <template slot-scope="scope">
          <el-switch  v-model="scope.row.showStatus"
                  active-color="#13ce66"
                 inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="handleShowStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['Community:charity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['Community:charity:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!-- 图片预览   放在表格外面，这是个弹出狂-->
      <el-dialog :visible.sync="dialogVisible" :modal="false" title="图片预览" width="50%">
        <img :src="previewpic" alt=""  width="100%" />
        <span slot="footer" class="dialog-footer">
          </span>
       </el-dialog>
  <!-- 图片预览 -->
    <!-- 添加或修改慈航公益对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
          <el-form-item label="图片地址" prop="pcUrl">
          <el-upload
          class="avatar-uploader"
          ref="upload"
          :action="upload.url"
          :headers="upload.headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width:100px;height:100px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        </el-form-item>
         <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入慈善活动名称" />
        </el-form-item>
         <el-form-item label="活动简述" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动简述" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="telPhone">
          <el-input v-model="form.telPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="目标金额" prop="targetMoney">
          <el-input v-model="form.targetMoney" placeholder="请输入目标金额（例如：100.00）" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择慈善活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择慈善活动结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否置顶" prop="isCarousel">
           <el-radio v-model="form.isCarousel" :label="0">是</el-radio>
          <el-radio v-model="form.isCarousel" :label="1">否</el-radio>
        </el-form-item>
        <el-form-item label="置顶排序" prop="stickSort">
          <el-input v-model="form.stickSort" placeholder="请输入置顶排序" />
        </el-form-item>
        <el-form-item label="海报地图" prop="bottomUrl">
         <el-col :span="12">
          <el-row>
          <el-radio v-model="form.postType" :label="1" @change="getPostType">海报底图1</el-radio>
          </el-row>
          <el-row>
          <el-radio v-model="form.postType" :label="2" @change="getPostType">海报底图2</el-radio>
           </el-row>
          <el-radio v-model="form.postType" :label="3" @change="getPostType">自定义海报底图</el-radio>
         </el-col>
         <el-col :span="12">
         <img :src=posturl1 style="width: 110px; padding: 4px;border:1px dashed #a9a9a9" v-if="form.postType==1"  @click="previewPic(posturl1)">
         <img :src=posturl2 style="width: 110px; padding: 4px;border:1px dashed #a9a9a9" v-if="form.postType==2"  @click="previewPic(scope.posturl2)">
         <el-upload v-if="form.postType==3"
          class="avatar-uploader"
          ref="upload"
          :action="upload.url"
          :headers="upload.headers"
          :show-file-list="false"
          :on-success="handlePosturSuccess"
          >
          <img v-if="posturl3" :src="posturl3" class="avatar" style="width:100px;height:100px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
         </el-col>
        </el-form-item>
        <el-form-item label="活动地址" prop="detailedAddress">
         <el-input v-model="form.detailedAddress"/>
          <div style="width:100%;border: 2px solid #ced4da;padding: 2px;margin: 10px 0">
              <iframe id="mapPage" style="width: 100%;height: 600px;z-index: 999" frameborder=0
                    src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=5OVBZ-27I6W-5LNRB-OWUIN-FUCVF-5SF6P&referer=云社群-H5">
              </iframe>
          </div>
        </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <div class="fromDiv">
           <el-form-item label="活动内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
          </div>
        </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <!-- 图片预览   放在表格外面，这是个弹出框-->
      <el-dialog :visible.sync="dialogVisible" :modal="false" title="图片预览" width="50%">
        <img :src="previewpic" alt=""  width="100%" />
        <span slot="footer" class="dialog-footer">
          </span>
       </el-dialog>
  <!-- 图片预览 -->
  </div>
</template>

<script>
import { listCharity, getCharity, delCharity, addCharity, updateCharity,changeNoticeStatus,changeIsCarouselStatus,changeShowStatusStatus } from "@/api/Community/charity";
import { getToken } from "@/utils/auth";
export default {
  name: "Charity",
  data() {
    return {
    dialogVisible: false,
    previewpic: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 慈航公益表格数据
      charityList: [],
      // 弹出层标题
      title: "",
      imageUrl:'',
      // 是否显示弹出层
      open: false,
       //上传参数
      upload:{
          // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/content/advertising/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        asId: null,
        userId: null,
        telPhone: null,
        name: null,
        title: null,
        content: null,
        type: null,
        contacts: null,
        pcUrl: null,
        donorMoney: null,
        targetMoney: null,
        startTime: null,
        endTime: null,
        address: null,
        collectNumber: null,
        charityNumber: null,
        status: null,
        isCarousel: null,
        stickSort: null,
        postUrl: null,
        bottomUrl: null,
        postType: null,
        showStatus: null,
       
      },
      mainVm:{},
      //海报底图
      posturl1:'https://shequncloud.oss-cn-shenzhen.aliyuncs.com/ht-images/test/43generationCharityPayLink.png',
      posturl2:'https://shequncloud.oss-cn-shenzhen.aliyuncs.com/yunshequn-images/dtImgCharityCustomTwo.png',
      posturl3:'',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        asId: [
          { required: true, message: "协会id不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "发起人id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "慈善活动名称不能为空", trigger: "blur" }
        ],
        pcUrl: [
          { required: true, message: "图片地址，多张用；分隔不能为空", trigger: "blur" }
        ],
        donorMoney: [
          { required: true, message: "已捐赠金额不能为空", trigger: "blur" }
        ],
        targetMoney: [
          { required: true, message: "目标金额不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "慈善活动开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "慈善活动结束时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  mounted(){
      //接收来自其他页面的消息并判断发送者
    window.addEventListener("message", this.onMessage);
  },
  created() {
    this.getList();
  },
  methods: {
    createIndex(index){
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    
    /** 查询慈航公益列表 */
    getList() {
      this.loading = true;
      listCharity(this.queryParams).then(res => {
        this.charityList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
   //切换海报底图
    getPostType(val){
      console.info(val);
      this.form.postType=val;
    },
    
  previewPic(url) {
           this.previewpic = url;
           this.dialogVisible = true;
        },
        //修改状态
         handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.id + '"公告吗？').then(function() {
        return changeNoticeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "2" : "0";
      });
    },
    //是否置顶
     handleIsCarouselChange(row) {
      let text = row.isCarousel === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.id + '"公告吗？').then(function() {
        return changeIsCarouselStatus(row.id, row.isCarousel);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isCarousel = row.isCarousel === "0" ? "2" : "0";
      });
    },
    //是否显示进度详情
     handleShowStatusChange(row) {
      let text = row.showStatus === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.id + '"公告吗？').then(function() {
        return changeShowStatusStatus(row.id, row.showStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.showStatus = row.showStatus === "0" ? "2" : "0";
      });
    },
     //上传图片
     handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code==200){
          this.form.pcUrl=res.data;
        }else{
          this.$modal.confirm("图片上传失败")
        }
      },
    //海报底图上传  
       handlePosturSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code==200){
          this.posturl3=res.data;
        }else{
          this.$modal.confirm("图片上传失败")
        }
      },      
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        asId: null,
        userId: null,
        telPhone: null,
        name: null,
        title: null,
        content: null,
        type: null,
        contacts: null,
        pcUrl: null,
        donorMoney: null,
        targetMoney: null,
        startTime: null,
        endTime: null,
        address: null,
        collectNumber: null,
        charityNumber: null,
        createTime: null,
        updateTime: null,
        status: 0,
        isCarousel: null,
        stickSort: null,
        postUrl: null,
        bottomUrl: null,
        postType: null,
        showStatus: 0,
        detailedAddress: null,
         areaName:null
      };
      this.resetForm("form");
    },
     //获取地址
    onMessage(event) {
	  // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
	  var loc = event.data;
	  if (loc && loc.module == 'locationPicker') {
      //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
	      console.log('location', loc);
        if(loc.poiname=='我的位置'){
          this.$modal.confirm("请重新选择地址")
        }
        this.form.detailedAddress=loc.cityname+"·"+loc.poiname;
        let obj={};
        obj.name=loc.poiname;
        obj.coord=loc.latlng.lat+","+loc.latlng.lng;
        this.form.address=JSON.stringify(obj);
        console.info(this.form.address);
	      this.mainVm.dialogFormVisibleMap=false;
	  }
},
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.postType=2;
      this.open = true;
      this.title = "添加慈航公益";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCharity(id).then(res => {
        console.info(res)
        this.form = res.data;
        this.imageUrl=res.data.pcUrl;
        this.open = true;
        this.title = "修改慈航公益";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCharity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCharity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除慈航公益编号为"' + ids + '"的数据项？').then(function() {
        return delCharity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('Community/charity/export', {
        ...this.queryParams
      }, `charity_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style >

 .el-tooltip__popper{
    max-width:20%;
  }
  .el-tooltip__popper,.el-tooltip__popper.is-dark{
    background:rgb(27, 100, 190) !important;
    color: #fff !important;
    line-height: 20px;
    font-size: 15px;
  }

  .fromDiv{
    height: 800px;
    overflow: auto;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
